using System;
using System.Web;
using System.Web.UI;
using System.Collections.Generic;
using System.Xml;
using Coffee.SurveyControls;

namespace Coffee
{

    public class ControlList : Dictionary<string, Control>
    {
    }

    /// <summary>
    /// Summary description for Coffee
    /// </summary>
    public class SurveyManager : UserControl
    {
        //Control parent;
        XmlNode configuration;

        public ControlList SurveyControls;

        // need to find a better way to handle this
        // this is used by FindControl to allow code to arbitrarily call
        // Coffee's (recursive) FindControl method
        public static SurveyManager Instance
        {
            get { return (SurveyManager)HttpContext.Current.Session["CurrentCoffeeInstance"]; }
            set { HttpContext.Current.Session["CurrentCoffeeInstance"] = value; }
        }

        public new static object FindControl(string id)
        {
            //if (this.ID == id) return this;
            foreach (Control ctl in Instance.SurveyControls.Values)
            {
                if (ctl.GetType().BaseType == typeof(SurveyControl))
                {
                    object ctlFound = ((SurveyControl)ctl).FindControl(id);
                    if (ctlFound != null) return ctlFound;
                }
            }
            return null;
        }

        public SurveyManager(XmlNode configuration)
        {
            this.configuration = configuration;
            Instance = this;
        }

        public delegate void ControlAddedHandler(SurveyControl ctl);

        public ControlAddedHandler OnControlAdded;

        public void CreateControls()
        {
            XmlNodeList controls = configuration.SelectNodes("control");

            SurveyControls = new ControlList();

            foreach (XmlNode control in controls)
            {
                try
                {
                    SurveyControl ctl = null;
                    XmlAttribute ctlType = null;
                    if ((ctlType = control.Attributes["type"]) != null)
                    {
                        try
                        {

                            ctl = SurveyControlFactory.Create(this, control);

                            if (ctl == null)
                            {
                                ctl = SurveyControl.LoadControl("~/Controls/" + ctlType.Value + ".ascx", new object[] { this, control });
                            }
                        }
                        catch (Exception ex2)
                        {
                            throw new Exception(string.Format("Failed to load Control '{0}'", ctlType.Value), ex2);
                        }

                    }
                    else
                    {
                        throw new Exception("Attribute expected: type");
                    }
                    if (ctl != null)
                    {
                        ctl.ReloadData = reloadData;
                        SurveyControls.Add(Guid.NewGuid().ToString(), ctl);
                        this.Controls.Add(ctl);
                        if (OnControlAdded != null)
                            OnControlAdded(ctl);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error processing control in path '{0}' : {1}", Coffee.Parser.GetIDPath(configuration), ex.Message), ex);
                }

            }
        }

        public delegate string CallbackEventHandler(string args);

        public CallbackEventHandler CallBackEvent;

        public string ExecuteCallbacks(string args)
        {
            if (CallBackEvent != null)
                return CallBackEvent(args);
            return "";
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            CreateControls();
        }

        bool reloadData;

        public bool ReloadData { get { return reloadData; } set { reloadData = value; } }

        public bool Update()
        {
            bool result = true;
            if (SurveyControls != null)
            {
                foreach (Control ctl in SurveyControls.Values)
                {
                    if (typeof(SurveyControl).IsAssignableFrom(ctl.GetType()))
                    {
                        SurveyControl isctl = (SurveyControl)ctl;
                        result &= isctl.Validate();
                    }
                }

                if (result)
                {
                    foreach (Control ctl in SurveyControls.Values)
                    {
                        if (typeof(SurveyControl).IsAssignableFrom(ctl.GetType()))
                        {
                            SurveyControl isctl = (SurveyControl)ctl;
                            isctl.SaveData();
                        }
                    }
                }
            }

            return result;
            //return true;

        }

    }


}